// import token from './auth.js'

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function debounce(fn, delay) {
  let timer = null
  return function() {
    let args = arguments
    let context = this

    if (timer) {
      clearTimeout(timer)

      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    } else {
      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    }
  }
}

export function fixedNum(current = 0, total = 1, fixed = 2) {
  let rate = toFixed((current / total) * 100, fixed)
  return +rate
}

export function toFixed(n, fixed) {
  if (typeof n !== 'number') {
    return n
  }
  fixed = fixed || 2
  var sN = '' + n
  var reg = new RegExp('\\d+\\.\\d{' + (fixed + 1) + '}')
  var s = sN.match(reg)
  var diff = 1 / Math.pow(10, fixed)
  if (s) {
    var val = s[0]
    var len = val.length
    var v = val[len - 1]
    n = +val.substring(0, len - 1)
    if (v >= 5) {
      n += diff
      n = +n.toFixed(fixed)
    }
  }
  // n = n.toFixed(fixed)
  return n
}

export function addZero(n) {
  return n > 9 ? '' + n : '0' + n
}

export function getNewDate(date = new Date(), n = 0) {
  let newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  newDate.setDate(newDate.getDate() + n)
  return {
    sDate:
      newDate.getFullYear() +
      '-' +
      addZero(newDate.getMonth() + 1) +
      '-' +
      addZero(newDate.getDate()),
    newDate: newDate
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  let search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}


export const userRole =
  {
    '000000': 'admin'
  }[localStorage.getItem('distCode')] || 'user'

export const isAdmin = userRole === 'admin'

export default {
  // token,
  deepClone,
  debounce
}
